package egovframework.npqs.pqi.mobile.activity.approve;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.sds.BizAppLauncher.gov.aidl.GovController;
import com.sds.BizAppLauncher.gov.aidl.GovController.IGovCallback;

import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.activity.LoginActivity;
import egovframework.npqs.pqi.mobile.activity.PlaceOfficerActivity;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.QuarantineApproveItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.SanctnListItem;
import egovframework.npqs.pqi.mobile.jsonparser.ApproveDetailThread;
import egovframework.npqs.pqi.mobile.jsonparser.ApproveDetailThread.ApproveDetailThreadCallback;
import egovframework.npqs.pqi.mobile.jsonparser.ApproveResultThread;
import egovframework.npqs.pqi.mobile.jsonparser.ApproveResultThread.ApproveResultThreadCallback;

//결재	: 결재관리상세에서 하단 결재버튼을 누르면 뜨는 엑티비티
public class ApproveDetail extends Activity implements ApproveDetailThreadCallback, ApproveResultThreadCallback, 
											OnClickListener, OnItemSelectedListener
											, OnCheckedChangeListener{
	private TextView titleTxt;
	private AppStatus myapp;
	private Context context;
	
	private String resNo, resOffCd, value, success, gianSn;
	
	private ImageButton draftBtn, btnHome, btn_back;
	private TextView content1_1, content2_1, content2_2, content3_1, content3_2;
	private TextView content4_1, content4_2, navigation;
	private EditText content7_1, content9_1;
	private Spinner content5_1;
	private CheckBox chk_edi;
	private CheckBox plants_qurant, free_export_plant, lmo_certificate, opinion_synthesize;
	private RelativeLayout detail_layout05;
	
	private QuarantineApproveItem approveItem;
	private ApproveDetailThread approveThread;
	private ApproveResultThread approveResultThread;
	
	private ArrayList<SanctnListItem> sanArrList;
	
	private ArrayList<String> spinSanArrList;
	
	private Button footerBtn01, footerBtn02, footerBtn03, footerBtn04;	// 하단 버튼
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	private final static int MSG_QUARANTINE_UPDATE_COMPLETED = 3;
	
	private ImageButton gian_button;
	private EditText gian_person;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
    
    JSONObject resultData;
	JSONObject resultMaster;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("결재");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_approve_detail);
		
		Intent intent = getIntent();
		
		value = intent.getStringExtra("value");
		if(value.equals("0")){
			resNo = intent.getStringExtra("resNo");
			resOffCd = intent.getStringExtra("resOffCd");	
		}else{
			resOffCd = intent.getStringExtra("fullResNo");	
		}
		
		init();
	}
	
	private void init(){
		//context = getApplicationContext();
		context = this;
		myapp = (AppStatus) getApplicationContext();
		myapp.startBroker(context);
		
		gianSn = myapp.getLoginItem().getUserSn();
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("결재");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		
		/*loginBtn = (ImageButton)findViewById(R.id.btnLogin);
		loginBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.appFinish(ApproveDetail.this);				
			}
		});*/
		
		btn_back = (ImageButton)findViewById(R.id.btn_back);
		btn_back.setVisibility(View.VISIBLE);
		btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setDataDetailLoadState(false);
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		detail_layout05 = (RelativeLayout)findViewById(R.id.detail_layout05);
		
		footerBtn01 = (Button)findViewById(R.id.footer01Btn);
		footerBtn02 = (Button)findViewById(R.id.footer02Btn);
		footerBtn03 = (Button)findViewById(R.id.footer03Btn);
		footerBtn04 = (Button)findViewById(R.id.footer04Btn);
		
		//footerBtn01.setOnClickListener(this);
		footerBtn01.setBackgroundResource(R.drawable.f_blank_sel);
		
		footerBtn02.setOnClickListener(this);
		footerBtn03.setOnClickListener(this);
		footerBtn04.setOnClickListener(this);
		
		content1_1 = (TextView)findViewById(R.id.content_1_1);
		content2_1 = (TextView)findViewById(R.id.content_2_1);
		content2_2 = (TextView)findViewById(R.id.content_2_2);
		content3_1 = (TextView)findViewById(R.id.content_3_1);
		content3_2 = (TextView)findViewById(R.id.content_3_2);
		content4_1 = (TextView)findViewById(R.id.content_4_1);
		content4_2 = (TextView)findViewById(R.id.content_4_2);
		content5_1 = (Spinner)findViewById(R.id.content_5_1);
		
		content7_1 = (EditText)findViewById(R.id.content_7_1);
		
		plants_qurant = (CheckBox)findViewById(R.id.plants_qurant);
		free_export_plant = (CheckBox)findViewById(R.id.free_export_plant);
		lmo_certificate = (CheckBox)findViewById(R.id.lmo_certificate);
		opinion_synthesize = (CheckBox)findViewById(R.id.opinion_synthesize);
		
		plants_qurant.setOnCheckedChangeListener(this);
		free_export_plant.setOnCheckedChangeListener(this);
		lmo_certificate.setOnCheckedChangeListener(this);
		opinion_synthesize.setOnCheckedChangeListener(this);
		
		content9_1 = (EditText)findViewById(R.id.content_9_1);
		
		chk_edi = (CheckBox)findViewById(R.id.chk_edi);
		
		draftBtn = (ImageButton)findViewById(R.id.button_6_1);
		draftBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent01 = new Intent(ApproveDetail.this, DraftExamSearchActivity.class);
				//intent01.putExtra("userNm", content10_2.getText().toString());
				startActivityForResult(intent01, 1);
			}
		});
		
		//기안자 추가
		gian_button = (ImageButton)findViewById(R.id.gian_button);
		gian_person = (EditText)findViewById(R.id.gian_person_edit);
		gian_person.setText(myapp.getLoginItem().getUserNm());
		
		gian_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent01 = new Intent(ApproveDetail.this, PlaceOfficerActivity.class);
				intent01.putExtra("userNm", gian_person.getText().toString());
				startActivityForResult(intent01, 2);
			}
		});
		
		gian_person.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				gian_person.setText("");
			}
		});
		
		myapp.showDialogNo(context);
		temp = "처음검색";
		//asyncTaskIsConnectedVPN();
		threadStart();
		
	}
	
	private void searchDetail(){
		myapp.showDialogNo(context);	// 페이지가 로드 될때 다이얼로그 출력.
		temp = "조건검색";
		//asyncTaskIsConnectedVPN();
		threadStart();
	}
	
	public void threadStart(){
		if("조건검색".equals(temp)){
    		approveThread = new ApproveDetailThread(context, this, resOffCd, resNo, value
    				, AppStatus.getmUserId());
    		approveThread.start();	
    	}
    	if("처음검색".equals(temp)){
    		approveThread = new ApproveDetailThread(context, this, resOffCd, resNo, value
    				, AppStatus.getmUserId());
    		approveThread.start();	
    	}
    	if("결재".equals(temp)){
    		approveResultThread = new ApproveResultThread(context, ApproveDetail.this
    				, resultData.toString(), value, AppStatus.getmUserId());
    		approveResultThread.start();
    	}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			if(resultCode == 1){
				content7_1.setText(data.getStringExtra("draftBody"));
				approveItem.setDrafCd(data.getStringExtra("drafCd"));
			}else{
				Log.i("resultCode","resultCode  0 아님");
			}
			break;
			
		case 2:
			if(resultCode == 1){
				gian_person.setText(data.getStringExtra("userNm"));
				gianSn = data.getStringExtra("userSn");
				String reData = data.getStringExtra("allInsttNm");
				//String reData = "식물검역1과";
				for(int i=0; i<spinSanArrList.size(); i++){
					if(spinSanArrList.get(i).toString().equals(reData)){
						content5_1.setSelection(i);
						break;
					}
				}
				
			}else{
				Log.i("resultCode","resultCode  0 아님");
			}
			break;
			
		default:
			break;
		}
	}
	
	private void layoutSetting() {
		content1_1.setText(approveItem.getOffCd()+"-"+approveItem.getRecNo());
		content2_1.setText(approveItem.getFullResNo());
		content2_2.setText(approveItem.getFieDe());
		content3_1.setText(approveItem.getResDe());
		content3_2.setText(approveItem.getResultProgrsNm());
		content4_1.setText(approveItem.getDrafDate());
		content4_2.setText(approveItem.getProgrsNm());
		
		if(approveItem.getEdiYn().equals("Y")){
			chk_edi.setChecked(true);
		}else{
			chk_edi.setChecked(false);
		}
		
		content7_1.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				approveItem.setDrafBody(s.toString());
			}
		});
		
		content9_1.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				approveItem.setDrafRem(s.toString());
			}
		});
		
		sanArrList = approveItem.getSanctnList();
		if(sanArrList.size() > 0 && sanArrList != null){
			spinSanArrList = new ArrayList<String>();
			for (int i = 0; i < sanArrList.size(); i++) {
				spinSanArrList.add(sanArrList.get(i).getKwaNm());
			}
			
			ArrayAdapter<String> sanAdapter 
			= new ArrayAdapter<String>(context,  R.layout.spinner_item, spinSanArrList);
			
			sanAdapter.setDropDownViewResource(R.layout.spinner_item);
			
			content5_1.setAdapter(sanAdapter);
		}else{
			detail_layout05.setVisibility(View.GONE);
		}
		content7_1.setText(approveItem.getDrafBody());
		
		String[] temp = approveItem.getDrafRem().split(",");
		for(int i =0; i<temp.length; i++){
			if(temp[i].trim().equals("식물검역증 별첨")){
				plants_qurant.setChecked(true);
			}
			if(temp[i].trim().equals("무환식물")){
				free_export_plant.setChecked(true);
			}
			if(temp[i].trim().equals("LMO수입승인서")){
				lmo_certificate.setChecked(true);
			}
			if(temp[i].trim().equals("검역종합의견")){
				opinion_synthesize.setChecked(true);
			}
		}
		
	}
	

	@Override
	public void OnApproveDetailCompleted(boolean isNetworkConntected,
			QuarantineApproveItem approveItem, String message) {
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(approveItem != null) {
			this.approveItem = approveItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
		
	}

	@Override
	public void OnApproveDetailError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
		
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				layoutSetting();
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				myapp.utilm.ShowDialog(ApproveDetail.this, "실패", errMsg, 20);
				
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(ApproveDetail.this, "실패", "네트워크에러", 20);
				break;
			case MSG_QUARANTINE_UPDATE_COMPLETED:
				new AlertDialog.Builder(ApproveDetail.this)
				.setTitle("저장")
				.setMessage(success)
				.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							searchDetail();
						} catch (Exception e) {

						}
					}
				})
				.setCancelable(false)
				.show();
				break;
			default:
				break;
			}
		}
	};
	
	private void approveRequest(){
		resultData = new JSONObject();
		resultMaster = new JSONObject();
		try {
			if(value.equals("0")){
				resultMaster.put("fullResNo", approveItem.getFullResNo());	
			}else{
				resultMaster.put("fullResNo", resOffCd);
			}
			
			resultMaster.put("draftCd", approveItem.getDrafCd());
			resultMaster.put("draftBody", content7_1.getText().toString());
			resultMaster.put("draftRem", content9_1.getText().toString());
			resultMaster.put("formNo", approveItem.getFormNo());
			if(sanArrList.size() > 0){
				resultMaster.put("handleKwa", approveItem.getHandleKwa());
			}else{
				resultMaster.put("handleKwa", "");
			}
			if(chk_edi.isChecked()){
				resultMaster.put("ediYn", "Y");	
			}else{
				resultMaster.put("ediYn", "N");
			}
			
			resultMaster.put("updNamCd", gianSn);
	        
	        resultData.put("resultData", resultMaster);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		Log.i("draft","draft = " + resultData.toString());
		
		myapp.showDialogNo(context);
		temp = "결재";
		//asyncTaskIsConnectedVPN();
		threadStart();
		
	}

	@Override
	public void OnApproveResultCompleted(boolean isNetworkConntected,
			String result, String message) {
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(!result.equals("")) {
			this.success = result;
			//결재가 되면 상세페이지에서 리로딩 되어야 한다.
			myapp.setDataDetailLoadState(true);
			
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_UPDATE_COMPLETED;
			handler.sendMessage(msg);
		}
		
	}

	@Override
	public void OnApproveResultUpdatelError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}
	
	@Override
	public void onClick(View v) {
		Intent intent ;
		switch (v.getId()) {
		case R.id.footer01Btn:	// 목록 버튼
			onBackPressed();
			break;
			
		case R.id.footer02Btn:	// 결재 버튼
			if(approveItem.getProgrsNm().equals("결재완료")){
				new AlertDialog.Builder(ApproveDetail.this)
				.setTitle("결재")
				.setMessage("이미 결재 하셨습니다.")
				.setPositiveButton("예", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							
						} catch (Exception e) {

						}
					}
				})
				.setCancelable(false)
				.show();
			}else{
				new AlertDialog.Builder(ApproveDetail.this)
				.setTitle("")
				.setMessage("검역신청번호 : " + approveItem.getOffCd() +"-"+ approveItem.getRecNo()+"\n전결하시겠습니까?")
				.setPositiveButton("예", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							approveRequest();
						} catch (Exception e) {

						}
					}
				})
				.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				})
				.setCancelable(false)
				.show();
			}
			break;

		default:
			break;
		}
		
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		switch (view.getId()) {
		case R.id.content_6_1:
			approveItem.setHandleKwa(sanArrList.get(position).getKwaCd());
			break;
		default:
			break;
		}
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {}
	
	@Override
	protected void onResume() {
		
		if(myapp.isFinishState()||myapp.isAbleHome()){
			finish();
		}
		if(myapp.isDataDetailLoadState()){
			myapp.startBroker(context);
			layoutSetting();
			myapp.setDataDetailLoadState(false);
		}
		super.onResume();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		String editStr = content9_1.getText().toString();
		switch (buttonView.getId()) {
		case R.id.plants_qurant:
			if(isChecked){
				if(editStr.equals("")){
					editStr = "식물검역증 별첨";
				}else{
					editStr += ",식물검역증 별첨";
				}
			}else{
				if(editStr.contains(",식물검역증 별첨")){
					editStr = editStr.replace(",식물검역증 별첨", "");
				}else if(editStr.contains("식물검역증 별첨")){
					editStr = editStr.replace("식물검역증 별첨", "");
				}
			}
			break;
		case R.id.free_export_plant:
			if(isChecked){
				if(editStr.equals("")){
					editStr = "무환식물";
				}else{
					editStr += ",무환식물";
				}
			}else{
				if(editStr.contains(",무환식물")){
					editStr = editStr.replace(",무환식물", "");
				}else if(editStr.contains("무환식물")){
					editStr = editStr.replace("무환식물", "");
				}
			}
			break;
		case R.id.lmo_certificate:
			if(isChecked){
				if(editStr.equals("")){
					editStr = "LMO수입승인서,훈증소독결과서별점";
				}else{
					editStr += ",LMO수입승인서,훈증소독결과서별점";
				}
			}else{
				if(editStr.contains(",LMO수입승인서,훈증소독결과서별점")){
					editStr = editStr.replace(",LMO수입승인서,훈증소독결과서별점", "");
				}else if(editStr.contains("LMO수입승인서,훈증소독결과서별점")){
					editStr = editStr.replace("LMO수입승인서,훈증소독결과서별점", "");
				}
			}
			break;
		case R.id.opinion_synthesize:
			if(isChecked){
				if(editStr.equals("")){
					editStr = "검역종합의견";
				}else{
					editStr += ",검역종합의견";
				}
			}else{
				if(editStr.contains(",검역종합의견")){
					editStr = editStr.replace(",검역종합의견", "");
				}else if(editStr.contains("검역종합의견")){
					editStr = editStr.replace("검역종합의견", "");
				}
			}
			break;

		default:
			break;
		}
		content9_1.setText(editStr);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}

	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
}

